//
//  TJAdController.m
//  Teleport
//
//  Created by botu　 on 2020/8/1.
//  Copyright © 2020 byx. All rights reserved.
//

#import "TJAdController.h"
#import "TJSelectCoinController.h"
#import "TJAdSelectPayWayController.h"
#import <MBProgressHUD.h>
@interface TJAdController ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UIView *coinBgView;
@property (weak, nonatomic) IBOutlet UILabel *coinNameLabel;
@property (weak, nonatomic) IBOutlet UIView *piceBgView;
/**溢价 */
@property (weak, nonatomic) IBOutlet UITextField *piceTextField;

/**起始报价 */

@property (weak, nonatomic) IBOutlet UILabel *startPriceLabel;

/**可接受价格 */
@property (weak, nonatomic) IBOutlet UIView *acceBgView;
/**可接受价格 textF */
@property (weak, nonatomic) IBOutlet UITextField *acceTextField;
/**可接受价格 label */
@property (weak, nonatomic) IBOutlet UILabel *acceLabel;

/**数量 */
@property (weak, nonatomic) IBOutlet UIView *numBgView;
/**交易数量 */
@property (weak, nonatomic) IBOutlet UITextField *numTextField;

/**可用金额 */
@property (weak, nonatomic) IBOutlet UILabel *avaiLabel;


/**金额 */
@property (weak, nonatomic) IBOutlet UIView *amountBgView;
/**g购买金额 */
@property (weak, nonatomic) IBOutlet UITextField *amountTextField;


/**成交 */
@property (weak, nonatomic) IBOutlet UIView *dealBgView;
/**最高成交金额 */
@property (weak, nonatomic) IBOutlet UILabel *dealLabel;


/**支付方式 */
@property (weak, nonatomic) IBOutlet UIView *payBgView;

@property (weak, nonatomic) IBOutlet UIView *payIconBgView;


@property (weak, nonatomic) IBOutlet UIButton *coimmitBtn;

/**最大溢价 */
@property (assign, nonatomic) NSInteger maxRatio;
/**最小溢价 */
@property (assign, nonatomic) NSInteger minRatio;

/**支付方式 */
@property (copy, nonatomic) NSString *payType;
/**币种 */
@property (weak, nonatomic) IBOutlet UILabel *coinName;

@end

@implementation TJAdController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.payType = @"";
    //添加边框
    [self.coinBgView addRoundedLine];
    [self.piceBgView addRoundedLine];
    [self.acceBgView addRoundedLine];
    [self.numBgView addRoundedLine];
    [self.amountBgView addRoundedLine];
    [self.dealBgView addRoundedLine];
    
    //支付方式添加点击
    [self.payBgView addTapGesturesWithTarget:self action:@selector(payClick)];
    self.piceTextField.delegate = self;
    self.acceTextField.delegate = self;
    self.numTextField.delegate = self;
    self.amountTextField.delegate = self;
    [self.piceTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [self.numTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [self.amountTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    if (self.type == 1) {//出售
        
        self.acceLabel.text = @"可接受最低价格";
        [self.coimmitBtn setTitle:@"发布出售广告" forState:UIControlStateNormal];
        self.amountTextField.placeholder = @"出售金额";
    }
    
    
    
    
    //获取溢价
    [self loadPice];
    
    //获取当前币子的价格
    [self loadCoinPice:self.coinNameLabel.text];
    
    //获取账户可用usdt
    [self loadAvailableUSDT];
    //最终报价 = 指数价格(当前价格)*(1+溢价指数(溢价))
    //最高成交额 =  最终报价* 数量
}


#pragma mark ---------------data------------------
//获取溢价
- (void)loadPice {
    weakify(self)
    [TJNetworking.shareNetworking POSTNew:@"otc/order/ratioConfig" parameters:nil success:^(NSDictionary * _Nonnull responseObject, NSDictionary *data) {
        weakself.minRatio = 0-[data[@"minRatio"] integerValue];
        weakself.maxRatio = [data[@"maxRatio"] integerValue];
        
        
    } failure:^(NSError * _Nonnull error) {
        
        [TJHud showAutoHideMessage:error.localizedFailureReason];
    }];
}
//获取当前币子的价格
- (void)loadCoinPice:(NSString *)coinName {
    
    weakify(self)
    [TJNetworking.shareNetworking POSTNew:@"otc/order/getPrice" parameters:@{@"currency":coinName ?: @""} success:^(NSDictionary * _Nonnull responseObject, NSDictionary *data) {
        
        weakself.startPriceLabel.text = [responseObject[@"result"] stringValue];
        
    } failure:^(NSError * _Nonnull error) {
        
        [TJHud showAutoHideMessage:error.localizedFailureReason];
    }];
}
//获取账户可用usdt
- (void)loadAvailableUSDT{
    
    weakify(self)
    [TJNetworking.shareNetworking GET:@"member/balance/getBalanceList" parameters:@{@"currency":@"USDT",@"userId":TJUserInfo.readInfo.userId} success:^(NSDictionary * _Nonnull responseObject, NSDictionary *data) {
        NSArray *balances = data[@"balances"];
        NSDictionary *dic = balances.firstObject;
        weakself.avaiLabel.text = [dic[@"fbBalance"] stringValue];
        
    } failure:^(NSError * _Nonnull error) {
        
        [TJHud showAutoHideMessage:error.localizedFailureReason];
    }];
}
/**切换 */
- (IBAction)changeBtnClick {
    TJSelectCoinController *selectCoinController = [[TJSelectCoinController alloc] init];
    weakify(self)
    [selectCoinController setSelectComplete:^(NSString * _Nonnull coinName) {
        NSLog(@"name=%@", coinName);
        weakself.coinNameLabel.text = coinName;
        weakself.coinName.text = coinName;
        //获取当前币子的价格
        [weakself loadCoinPice:coinName];
        
    }];
    [self presentViewController:selectCoinController animated:NO completion:nil];
}
/**加 */
- (IBAction)addBtnClick {
    if (self.piceTextField.text.integerValue >= self.maxRatio ) {
        return;
    }
    NSInteger textNum =  self.piceTextField.text.integerValue;
    textNum += 1;
    self.piceTextField.text = @(textNum).stringValue;
    /**最高成交额 */
    [self maxMoney];
}
/**减 */
- (IBAction)decBtnClick {
    if (self.piceTextField.text.integerValue <= self.minRatio) {
        return;
    }
    NSInteger textNum =  self.piceTextField.text.integerValue;
    textNum -= 1;
    self.piceTextField.text = @(textNum).stringValue;
    /**最高成交额 */
    [self maxMoney];
    
}
/**支付方式 */
- (void)payClick {
    TJAdSelectPayWayController *selectPayWayController = [[TJAdSelectPayWayController alloc] init];
    weakify(self)
    [selectPayWayController setSelectComplete:^(NSArray<TJCellStyleModel *> * _Nonnull models) {
        
        [weakself payIconImages:models];
    }];
    [self presentViewController:selectPayWayController animated:NO completion:nil];
}

-(void)payIconImages:(NSArray<TJCellStyleModel *> *)models {
    int margeX = 5;
    CGFloat imageW = 12;
    [self.payIconBgView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    NSMutableArray *payArray = @[].mutableCopy;
    for (int i = 0; i < models.count; i++) {
        TJCellStyleModel *model = models[i];
        UIImageView *imageV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:model.icon]];
        [self.payIconBgView addSubview:imageV];
        CGFloat imageX =self.payIconBgView.frame.size.width - i * (imageW + margeX);
        imageV.frame = CGRectMake(imageX, 0, imageW, imageW);
       
        [payArray addObject:model.identification];
    }
    
    self.payType = [payArray componentsJoinedByString:@"-"];
}
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(nonnull NSString *)string {
    
    if (textField == self.amountTextField || textField == self.numTextField || textField == self.acceTextField) {
        // 限制第一位不能是小数点
        if(textField.text.length == 0 && [string isEqualToString:@"."])return NO;
        //第一位补位零
        if(textField.text.length == 0 && [string isEqualToString:@"0"])return NO;
        
    }
    
    return  YES;
    
}

- (void)textFieldDidChange:(UITextField *)textField {
    

    
    if (self.piceTextField.text.length && self.acceTextField.text.length && self.numTextField.text.length && self.amountTextField.text.length) {
        self.coimmitBtn.backgroundColor = UIColor.tj_mainColor;
        self.coimmitBtn.enabled = YES;
    }else{
        self.coimmitBtn.backgroundColor =UIColor_Hex(0xC6C6C8);
        self.coimmitBtn.enabled = NO;
    }
    
    /**最高成交额 */
    [self maxMoney];
    
}

/**最高成交额 */
- (void)maxMoney {
    //最终报价 = 指数价格(当前价格)*(1+溢价指数(溢价率))
    //最高成交额 =  最终报价* 数量
    
    double finNum = self.startPriceLabel.text.doubleValue * (1 + self.piceTextField.text.integerValue/100.00);
    
    double money = finNum * self.numTextField.text.doubleValue;
    NSString *moneyStr = [NSString stringWithFormat:@"%f",money];
    self.dealLabel.text = [Tools CNYString:moneyStr];
    
}
- (IBAction)commitBtnClick {
    
      if (self.amountTextField.text.doubleValue >  self.dealLabel.text.doubleValue) {
            [TJHud showAutoHideMessage:@"购买金额不能大于最高成交额"];
          return;
           }
    
    if ([self.payType isEqualToString:@""]) {
      [TJHud showAutoHideMessage:@"请选择支付方式"];
    return;
     }
    
    //0.买单1.卖单
     NSString *direction = self.type == 0 ?@"BUY":@"SELL";

     NSDictionary *parameters = @{
         
         @"userId": TJUserInfo.readInfo.userId,
         @"upDownNumber": self.piceTextField.text,
         @"num": self.numTextField.text,
         @"minPrice": self.amountTextField.text,
         @"direction":direction,
         @"payType":self.payType,
         @"currency":self.coinNameLabel.text,
         @"extremum":self.acceTextField.text
     };
     
 
     [TJNetworking.shareNetworking POSTNew:@"otc/order/orderReleasing" parameters:parameters success:^(NSDictionary * _Nonnull responseObject, NSDictionary *data) {
         
      [TJHud showAutoHideMessage:@"发布成功".localizedString];
         [self.navigationController popViewControllerAnimated:YES];
     } failure:^(NSError * _Nonnull error) {
        [TJHud showAutoHideMessage:error.localizedFailureReason];
     }];
}
/**溢价提示 */
- (IBAction)piceBtnClick {
    [TJHud showTopAutoHideMessage:@"最终价格= 初始报价*（1+溢价%)".localizedString];
}
/**初始价格提示 */
- (IBAction)orgBtnClick {
     [TJHud showTopAutoHideMessage:@"币种当前价格".localizedString];
}
/**可接受提示 */
- (IBAction)accPiceBtnClick {
//       [TJHud showTopAutoHideMessage:@"当最终价格高于可接受最高价格，则最终价格等于此价格出售价格   最终价格低于可接受最高价格，则最终价格等于此价格".localizedString];
//    
//    self alertWithTitle:nil message:<#(nullable NSString *)#> leftButtonName:<#(nullable NSString *)#> rightButtonName:<#(nullable NSString *)#> leftButtonBlock:<#^(void)leftButtonBlock#> rightButtonBlock:<#^(void)rightButtonBlock#>

}

@end
